import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import _ from 'underscore';
import { DatePicker, Input, Modal, Checkbox,Switch, Button, Radio, message, Upload, Icon } from 'antd';
import 'react-select/dist/react-select.css';
import '../../../../dist/css/modal-file.css'
import { actions } from '../action/action';
import { ajax, merge } from '../../helper/helper';
import { getUploadParam, uploadCDN, validFileType } from '../../qiniu/uploadCDN.js';
import table from '../../charts/table';
import { ContentHeader } from '../../wrapper';
import { taskListTh, typeList, typeMap } from '../static/index';
import { setTimeout } from 'timers';

const confirm = Modal.confirm;
let taskOptions = {
    title: '',
    limit: 9,
    maxPageCount: 50,
    thead: taskListTh,
    pagebar: true,
    sorting: true,
    download: false,
    search: 'goodsName',
    only: false,
    setting: '#/tasks?listSetting=true',
    beforeRender: function (data, options) {
        return [
            <_Chkbox data={data} />,
            <_Recommend data={data} />,
            <GoodsName data={data} />,
            <GoodsCover data={data} />,
            <GoodsPrice data={data} />,
            <DiscountPrice data={data} />,
            <Discount data={data} />,
            <SoldonTime data={data} />,
            <_Operation data={data} />
        ]
    },
    trigger: ['pathname', 'time']
}

class TaskManage extends Component {
    componentWillMount() {
        var pathname = this.props.location.pathname.substring(1);
        this.props.setPathname(pathname);
    }

    componentDidUpdate() {
        var pathname = this.props.location.pathname.substring(1);
        this.props.setPathname(pathname);

    }

    render() {
        const listSetting = this.props.location.query.listSetting ? true : false;

        return (
            <div className="content">
                <TaskList options={taskOptions} />
                <Modal visible={listSetting} onCancel={() => history.back()} footer={[
                    <Button key="back" size="large" type="primary" onClick={() => history.back()}>关闭</Button>,
                ]}>
                </Modal>
            </div>
        );
    }

}

const _TaskManage = connect(
    state => {
        return {

        }
    },
    dispatch => {
        return {
            triggerAddTask: () => {
                dispatch({
                    type: 'trigger-add-task'
                });
            },
            setPathname: (pathname) => {
                dispatch({
                    type: 'set-path-name',
                    val: pathname
                });
            }
        }
    }
)(TaskManage);

class NewTask extends Component {
    disabledDate(time) {
        return time && time.valueOf() <= Date.now() - 86400000;
    }
    // 修改图片
    async handleUpdatePic(data){
        var newTask =  this.props.newTask;
        let self=this
        // 更新七牛云图片
         ////// 如果有封面图文件
         if (data.profile_image && data.profile_image.length) {
            if(newTask.profile_images_d) newTask.profile_images_d.goodsUrl=null
            if(data.profile_images_d) data.profile_images_d.goodsUrl=null
            for(var i of data.profile_image){
                await self.submitAllPic_d(i, 'goodsPic')    
            }
        }
        ////// 如果有详情图文件
        if (data.profile_images_d && data.profile_images_d.length) {
            if(data.profile_images_d) data.profile_images_d.goodsDesc=null
            if(newTask.profile_images_d) newTask.profile_images_d.goodsDesc=null
            console.log(data.profile_images_d.goodsDesc,'ccc')
            for(var i of data.profile_images_d){
                await self.submitAllPic_d(i,'goodsPic2')     
            }
        }
        await this.handleUpdate(data)
    }
    /////  修改上传七牛云
    async submitAllPic_d(i,picType2) {
        var newTask =  this.props.newTask;
        getUploadParam(function (token) {
            if (token) {
                var uploadParam = {
                    key: `${Date.now()}.${newTask.type}`,
                    token
                }
                //////////上传七牛
                uploadCDN(i, uploadParam, function (res) {
                    res = JSON.parse(res);
                    ////// 如果是封面就上传7N
                    if(picType2 === 'goodsPic'){
                        newTask.goodsUrl1=  newTask.goodsUrl1 ? 
                        newTask.goodsUrl1 + `,http://p1az9gcpw.bkt.clouddn.com/${uploadParam.key}?imageView2/2/w/70/h/70` :
                        `http://p1az9gcpw.bkt.clouddn.com/${uploadParam.key}?imageView2/2/w/70/h/70`
                    }
                    ////// 如果是详情就上传7N
                    if(picType2 === 'goodsPic2'){
                        newTask.goodsDesc1=  newTask.goodsDesc1 ? 
                        newTask.goodsDesc1 + `,http://p1az9gcpw.bkt.clouddn.com/${uploadParam.key}?imageView2/2/w/70/h/70` :
                        `http://p1az9gcpw.bkt.clouddn.com/${uploadParam.key}?imageView2/2/w/70/h/70`
                    }
                })
            }
        })
    }

    // 修改确认
    async handleUpdate(data){
        this.props.updateGoods(data)
    }

    /////////////////读取图片
    changeHeadortrait(picType,e) {
        var self = this,
            // reader = new FileReader(),
            // file = e.target.files[0], //// 选中的图片
            baseArr_cover=[],
            fileArr_cover=[],
            baseArr_detail=[],
            fileArr_detail=[],
            files = e.target.files, // 图片内容集合的数组
            type = files[0].type.split('/'), /// 数组形式的图片格式
            isTypeValid = validFileType(type[1], ['jpg', 'png', 'jpeg']);
            for(var i of files){
                var reader = new FileReader()
                if(isTypeValid){
                    fileArr_cover.push(i)
                    fileArr_detail.push(i),
                    reader.readAsDataURL(i) /// 读取每张图片内容
                    reader.onload = function (){ // 生成base64，上传图片 
                        baseArr_cover.push(this.result)
                        baseArr_detail.push(this.result)
                    }
                }
            }
            if(picType === 'coverPic'){
                //////  所有图片读取完毕，放入对象里，key是base64，val是file本身
                setTimeout(()=>{
                    self.props.changePicture({
                        profile_images:fileArr_cover , ///所有file 数组
                        profile_image_temps:baseArr_cover , /// base64,img的src 数组
                        type: type[1] })
                    },500)
            }
            if(picType === 'detailPic'){
                setTimeout(()=>{
                    self.props.changePicture_d({
                        profile_images_d:fileArr_detail , ///所有file 数组
                        profile_image_detail:baseArr_detail , /// base64,img的src 数组
                        type: type[1] })
                    },500)
            }
    }
   // 新增确定按钮,更改：删除了async submit
    submit () {
        var self = this;
        var { newTask } = this.props;
        // console.log(newTask.goodsUrl,'newTask')
        if( !newTask.goodsName ){
            return  message.error('请输入商品名称!',3)
        }
        if ( !newTask.profile_image ){
            return  message.error('请选择封面图!',3)
        }
        if ( !newTask.profile_images_d ){
            return  message.error('请选择详情图!',3)
        }
        if ( !newTask.goodsPrice ){
            return  message.error('请输入商品价格!',3)
        }
        // if ( !newTask.discountRate ){
        //     return  message.error('请输入折扣!',3)
        // }
        ////// 如果有封面图文件  删除了await submit
        if (newTask.profile_image.length) {
            newTask.profile_images_d.goodsUrl=''
            for(var i of newTask.profile_image){
                self.submitAllPic(i, 'goodsPic')                                               
            }
        }
        ////// 如果有详情图文件 删除了await submit
        if (newTask.profile_images_d.length) {
            newTask.profile_images_d.goodsDesc=''
            for(var i of newTask.profile_images_d){
             self.submitAllPic(i,'goodsPic2')                                         
            }
        }
        // console.log(newTask,'newTask')  
        // console.log(newTask.goodsUrl,'ooo') 
            self.submitAll() // 删除了await submit
    }
    submitAllPic(i,picType2) {
        var newTask =  this.props.newTask;
        getUploadParam(function (token) {
            if (token) {
                var uploadParam = {
                    key: `${Date.now()}.${newTask.type}`,
                    token
                }
                //////////上传七牛
                uploadCDN(i, uploadParam, function (res) {
                    res = JSON.parse(res);
                    ////// 如果是封面就上传7N
                    if(picType2 === 'goodsPic'){
                        newTask.goodsUrl=  newTask.goodsUrl ? 
                        newTask.goodsUrl + `,http://p1az9gcpw.bkt.clouddn.com/${uploadParam.key}?imageView2/2/w/70/h/70` :
                        `http://p1az9gcpw.bkt.clouddn.com/${uploadParam.key}?imageView2/2/w/70/h/70`
                        // console.log(newTask,'newTask')   //////  有值
                        // console.log(newTask.goodsUrl,'ooo')
                    }
                    ////// 如果是详情就上传7N
                    if(picType2 === 'goodsPic2'){
                        newTask.goodsDesc=  newTask.goodsDesc ? 
                        newTask.goodsDesc + `,http://p1az9gcpw.bkt.clouddn.com/${uploadParam.key}?imageView2/2/w/70/h/70` :
                        `http://p1az9gcpw.bkt.clouddn.com/${uploadParam.key}?imageView2/2/w/70/h/70`
                        // console.log(newTask,'newTask')  //////  有值
                    }
                }
            )
            }
        })
    }
    // 上传完图片后进行最后的提交
    submitAll() {
        var newTask=this.props.newTask
        console.log(newTask)
        console.log(newTask.goodsUrl,'goodsUrl')
        this.props.submitPics(newTask)
    }
    render() {
        const { isAddTask, triggerAddTask,createNewTask,commendStatus,
                newTask, isPending,changeDiscountRate, changeDiscount,
                changePriceTitle, changeGoodsName,changecommendStatus 
            } = this.props;
        const complete = newTask.wfTaskName.length == 0;
        const { TextArea } = Input;
        const modalInfo = {
            goodsName: newTask.goodsName,
            goodsPrice: newTask.goodsPrice,
            goodsUrl: newTask.goodsUrl,
            goodsId: newTask.goodsId,
            goodsDesc:newTask.goodsDesc,
            discountPrice:newTask.discountPrice,
            discountRate:newTask.discountRate,
            // commendStatus:newTask.commendStatus
        }
        let discountVal=modalInfo.goodsPrice*(modalInfo.discountRate*0.1)
        return (
            <div>
            <Modal title={newTask.modalType === 'add' ? '添加商品' : '修改商品'} footer={null} visible={isAddTask} onOk={() => { createNewTask(newTask) }} confirmLoading={!isPending} onCancel={triggerAddTask} footer={[
                <Button key="back" size="large" onClick={triggerAddTask}>取消</Button>,
                <Button key={'submit'} type="primary" size="large"  onClick={newTask.modalType === 'add' ?() => { this.submit(newTask) }:()=>{this.handleUpdatePic(newTask)}}>
                    确认
                </Button>,
            ]}>
                <form id="formData" role="form">
                    <div className="form-group">
                        <label htmlFor="task_title">商品名称</label>
                        <Input placeholder={'请输入商品名'} value={modalInfo.goodsName} size="large" id="gdsname" type="text" onChange={changeGoodsName} className="form-control" id="task_title" />
                    </div>
                    <div className="form-group">
                        <label>商品封面图</label>
                        <div className="file">
                            <input  type="file" 
                                    onChange={this.changeHeadortrait.bind(this,'coverPic')}
                            />
                            <span>请选择图片上传</span>
                        </div>
                        {
                            newTask.profile_image_temp && newTask.profile_image_temp.map((ims,index)=>
                                <img className="addImg" src={ims} key={index} />
                            )
                        }
                    </div>
                    <div className="form-group">
                        <label>商品详情图</label>
                        <div className="file">
                            <input  type="file" multiple="multiple" onChange={this.changeHeadortrait.bind(this,'detailPic')} />
                            <span>请选择图片上传</span>
                        </div>
                        {
                            newTask.profile_image_detail && newTask.profile_image_detail.map((ims,index)=>
                                <img className="addImg" src={ims} key={index} />
                            )
                        }
                    </div>
                    <div className="form-group">
                        <label>商品价格</label>
                        <Input placeholder={'请输入商品价格'} value={modalInfo.goodsPrice} size="large" type="number" onChange={changePriceTitle} className="form-control" />
                    </div>
                    <div className="form-group">
                        <label>折扣</label>
                        <Input placeholder={'请输入折扣'} type="text"   size="large" 
                        value={modalInfo.discountRate} 
                        onChange={changeDiscountRate} className="form-control" />
                    </div>
                    <div className="form-group">
                        <label>折扣价</label>
                        <Input  value={
                            modalInfo.goodsPrice && modalInfo.discountRate? discountVal.toFixed(1): ''
                            }
                        size="large" type="number"
                        onChange={changeDiscount} className="form-control" />
                    </div>
                </form>
            </Modal>
            </div>
        );
    }
}

const _NewTask = connect(
    function (state) {
        ////////刷新页面执行4次
        return {
            newTask: state.newTask,
            isAddTask: state.newTask.isAddTask,
            isPending: state.isPending,
            // isUpdate:true
        }
    },
    function (dispatch) {
        return {
            submitPics: (obj) =>{
                actions.submitPics(dispatch,obj);
            },
            updateGoods: (obj) =>{
                actions.updateGoods(dispatch,obj);
            },
            changePicture: (param) => {
                dispatch({
                    type: 'change-newtask-pic',
                    val: param
                });
            },
            // addSubmit: (param) => {
            //     console.log(param.goodsUrl,'param')
            //     dispatch({
            //         type: 'add-submit',
            //         val: param
            //     });
            // },
            changePicture_d: (param) => {
                dispatch({
                    type: 'change-newtask-pic_d',
                    val: param
                });
            },
            changeDiscountRate:(e)=>{
                dispatch({
                    type: 'change-task-discounutRate',
                    val: e.target.value
                });
            },
            changeDiscount:(e)=>{
                dispatch({
                    type: 'change-task-discounut',
                    val: e.target.value
                });
            },
            changePriceTitle: (e) => {
                dispatch({
                    type: 'change-task-title',
                    val: e.target.value
                });
            },
            changecommendStatus: (e)=>{
                dispatch({
                    type: 'change-task-commendStatus',
                    val: e.target.value
                });
            },
            changeGoodsName: (e) => {
                dispatch({
                    type: 'change-task-feedback',
                    val: e.target.value
                });
            },
            createNewTask: (task) => {
                actions.createNewTask(dispatch, task);
            },
        }
    }
)(NewTask);

export { _NewTask };

const TaskList = connect(
    function (state) {
        return state.taskList
    },
    function (dispatch) {
        return {
            getData: (params) => {
                actions.taskListSetPageIndex(dispatch, params);
                actions.taskListRenderData(dispatch, params);
                actions.taskListRequest(dispatch, params);
            }
        }
    }
)(table);


/////////// 店长推荐
class Recommend extends Component {
    
    render() {
        const { data, triggerShowTask, taskList,onSwitchChange,switchOn, checked, onCheck } = this.props;
        const index = taskList.data.findIndex((item) => { return item.wfTaskId == data.wfTaskId });
        const isChecked = _.contains(checked, index) || data.taskStatus == '4';
        return <div className="preview-media-limit preview-media-limit-group">
                <Switch onChange={onSwitchChange.bind(null,data)} defaultChecked={ switchOn }  />
            </div>
    }
}

const _Recommend = connect(
    state => {
        return {
            taskList: state.taskList,
            checked: state.doneChecked,
            switchOn:state.switchOn
        }   
    },
    dispatch => {
        return {
            triggerShowTask: (data) => {
                dispatch({
                    type: 'trigger-add-task',
                    val: data
                });
            },
            onSwitchChange:(data)=>{
                dispatch({
                    type: 'trigger-tuiJian',
                });
            },
            onCheck: (params, data) => {
                dispatch({
                    type: 'set-done-checked',
                    val: params
                });
                actions.markTaskComplete(data, dispatch);
            }
        }
    }
)(Recommend);



///////// 商品名称-列表内容
class GoodsName extends Component {
    render() {
        const { data } = this.props
        return <div className="preview-media-limit preview-media-limit-group">
            <p>{data.goodsName} </p>
        </div>
    }
}

///////////// 商品封面-列表内容
class GoodsCover extends Component {
    render() {
        const { data } = this.props
        return <div className="preview-media-limit preview-media-limit-group">
            <p className="goodsList-img">
                {/* <a href={data.goodsPic} target="_blank">{data.goodsPic}</a> */}
                <a href={data.goodsPic} target="_blank">
                    <img src={data.goodsPic} alt=""/>
                </a>
            </p>
        </div>
    }
}

////////////商品价格-列表内容
class GoodsPrice extends Component {
    render() {
        const { data } = this.props
        return <div className="preview-media-limit preview-media-limit-group">
            <p>{data.goodsPrice}</p>
        </div>
    }
}
///////////// 折扣价-列表内容
class DiscountPrice extends Component {
    render() {
        const { data } = this.props
        return <div className="preview-media-limit preview-media-limit-group ">
            <p>{data.discountPrice}</p>
        </div>
    }
}

////////////// 商品折扣
class Discount extends Component {
    render() {
        const { data } = this.props
        // var detail=data.goodsDesc && data.goodsDesc.split(',')[0]
        return <div className="preview-media-limit preview-media-limit-group">
            {/* {
                detail && detail.length && detail.map((ims,index)=>
                    <img className="detailImg" src={ims} key={index} alt=""/>
            )
            } */}
            {/* <img className="detailImg" src={detail} alt=""/> */}
            <p>{data.discountRate}</p>
        </div>
    }
}
////////////// 添加时间
class SoldonTime extends Component {
    render() {
        const { data } = this.props
        // var detail=data.goodsDesc && data.goodsDesc.split(',')[0]
        return <div className="preview-media-limit preview-media-limit-group">
            <p>{data.soldonTime}</p>
        </div>
    }
}

class Chkbox extends Component {

    render() {
        const { data, triggerShowTask, taskList, onChkChange,checked, onCheck } = this.props;
        return <div className="preview-media-limit preview-media-limit-group">
                <Checkbox onChange={()=>onChkChange(data)}></Checkbox>
        </div>
    }
}
const _Chkbox = connect(
    state => {
        return {
            
        }
    },
    dispatch => {
        return {
            onChkChange :(data) =>{
                console.log(data)
                dispatch({
                        type: 'trigger-chkbox-change',
                        val: data
                    });
            }
        }
    }
)(Chkbox);

////////////// 删除/修改-列表内容
class Operation extends Component {
    showConfirm(data) {
        let self = this;
        let { soldoutGoods } =this.props
        confirm({
            title: '确认下架此条商品吗?',
            okText: '确认',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                soldoutGoods(data)
            },
            onCancel() { },
        });
    }
    render() {
        const { data, triggerUpdateGoods, triggerDeleteTask, isDelete } = this.props;
        return (
            <div className="preview-media-limit preview-media-limit-group" style={{ cursor: 'pointer', color: '#43a6a5' }}>
                <a href="javascript: void(0)" onClick={() => triggerUpdateGoods(data)}>修改</a>
                <span className="ant-divider" />
                <a href="javascript: void(0)" onClick={this.showConfirm.bind(this, data)}>下架</a>
            </div>
        )
    }
}

const _Operation = connect(
    state => {
        return {
            // isDelete: state.newTask.isDelete
        }
    },
    dispatch => {
        return {
            soldoutGoods: (obj) =>{
                actions.soldoutGoods(dispatch,obj);
            },
            triggerUpdateGoods: (data) => {
                dispatch({
                    type: 'trigger-update-goods',
                    val: data,
                });
            },
            triggerAddTask: (data) => {
                console.log(data,'data')
                dispatch({
                    type: 'trigger-add-goods',
                    val: data
                });
            },
            triggerDeleteTask: (id) => {
                // dispatch({
                //     type: 'trigger-delete-task'
                // });

            },
            deleteGoods: (goodsId, resolve) => {
                actions.deleteGoods(dispatch, goodsId, resolve);
            }

        }
    }
)(Operation);





export default _TaskManage;